package com.sdhs.web.controller.system;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.banboocloud.Codec.BamboocloudFacade;
import com.sdhs.common.core.domain.R;
import com.sdhs.common.utils.BambooCloudUtils;
import com.sdhs.common.utils.validator.ValidatorUtils;
import com.sdhs.common.utils.validator.group.AddGroup;
import com.sdhs.common.utils.validator.group.DefaultGroup;
import com.sdhs.common.utils.validator.group.UpdateGroup;
import com.sdhs.system.syncdata.domain.SyncSysUser;
import com.sdhs.system.syncdata.dto.QueryParam;
import com.sdhs.system.syncdata.dto.SysDeptDTO;
import com.sdhs.system.syncdata.dto.SysRoleDTO;
import com.sdhs.system.syncdata.dto.SysUserDTO;
import com.sdhs.system.syncdata.service.*;
import com.sdhs.system.syncdata.util.ResultRole;
import com.sdhs.system.syncdata.util.ResultUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zhangmy
 * @date 2022/9/2010:38
 * @Description: 获取用户信息（统一认证平台）竹云
 */
@RestController
@RequestMapping("/public/data")
@Slf4j
public class SyncDataController {
    @Autowired
    private SchemaService schemaService;

    @Autowired
    private SyncSysDeptService sysDeptService;
    @Autowired
    private SyncSysUserService sysUserService;

    @Autowired
    private SyncSysRoleService sysRoleService;


    @Autowired
    private SyncSysUserDeptService sysUserDeptService;

    @PostMapping("/SchemaService")
    public Object schema(HttpServletRequest request){

        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("获取结构信息SchemaService{}", JSONUtil.toJsonStr(paramMap));
        Object schema = schemaService.getSchema(paramMap);
        return  schema;
    }

    /**
     * 用户相关
     * @return
     */

    @PostMapping("/UserCreateService")
    public Object add(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("新增SysUserDTO{}", JSONUtil.toJsonStr(paramMap));

        SyncSysUser dto=JSON.parseObject(JSON.toJSONString(paramMap), SyncSysUser.class);
        try {
            ValidatorUtils.validateEntity(dto, new Class[]{AddGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Object result= this.sysUserService.saveUser(dto);
        log.info("新增用户----"+result);
        return result;
    }
    @PostMapping("/UserUpdateService")
    public Object update(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("修改SysUserDTO{}", JSONUtil.toJsonStr(paramMap));

        SyncSysUser dto=JSON.parseObject(JSON.toJSONString(paramMap), SyncSysUser.class);
        log.info("修改SysUserDTO{}", JSONUtil.toJsonStr(dto));

        try {
            ValidatorUtils.validateEntity(dto, new Class[]{UpdateGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        com.sdhs.system.syncdata.util.Result result=new com.sdhs.system.syncdata.util.Result();
        result= (com.sdhs.system.syncdata.util.Result) this.sysUserService.updateUser(dto);

        log.info("修改用户----"+result);
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(result), "123456", "AES");
    }
    @PostMapping("/UserDeleteService")
    public Object delete(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("删除SysUserDTO{}", JSONUtil.toJsonStr(paramMap));

        SysUserDTO dto=JSON.parseObject(JSON.toJSONString(paramMap), SysUserDTO.class);
        log.info("删除SysUserDTO{}", JSONUtil.toJsonStr(dto));

        com.sdhs.system.syncdata.util.Result result=new com.sdhs.system.syncdata.util.Result();
        if(StringUtils.isNotBlank(dto.getBimUid())){
            result= (com.sdhs.system.syncdata.util.Result) this.sysUserService.delete(dto.getBimUid());
        }else{
            result.error("请填写要删除的id");
        }
        result.setBimRequestId(dto.getBimRequestId());
        log.info("删除用户----"+result);
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(result), "123456", "AES");
    }
    @PostMapping("/queryAllUserIdsService")
    public Object queryAllUserIdsService(HttpServletRequest request ){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("获取所有用户请求参数{}", JSONUtil.toJsonStr(paramMap));

        QueryParam queryParam=JSON.parseObject(JSON.toJSONString(paramMap), QueryParam.class);
        log.info("获取所有用户请求参数:{}", JSONUtil.toJsonStr(queryParam));

        ResultUser result=new ResultUser();
        result.setBimRequestId(queryParam.getBimRequestId());
        Object allUser = this.sysUserService.getAllUser(queryParam.getBimRequestId());
        log.info("获取所有用户----"+allUser);
        return allUser;
    }
    @PostMapping(value = "/QueryUserByIdService")
    public Object queryUserById(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("根据ID查询用户参数{}", JSONUtil.toJsonStr(paramMap));

        QueryParam queryParam=JSON.parseObject(JSON.toJSONString(paramMap), QueryParam.class);
        log.info("根据ID查询用户参数:{}", JSONUtil.toJsonStr(queryParam));

        Object sysUser = this.sysUserService.getUserById(queryParam.getBimRequestId(),queryParam.getBimUid());
        log.info("根据ID查询用户----"+sysUser);

        return sysUser;
    }


    /**
     * 机构相关操作
     * @param
     * @return
     */
    @PostMapping("/OrgCreateService")
    //HttpServletRequest request ,
    public Object OrgCreateService(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("添加SysDeptDTO{}", JSONUtil.toJsonStr(paramMap));

        SysDeptDTO dto=JSON.parseObject(JSON.toJSONString(paramMap), SysDeptDTO.class);
        log.info("添加SysDeptDTO{}", JSONUtil.toJsonStr(dto));

        try {
            ValidatorUtils.validateEntity(dto, new Class[]{AddGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Object result=  this.sysDeptService.save(dto);

        log.info("新增机构返回--------"+result);
        return result;
    }
    @PostMapping("/OrgUpdateService")
    public Object Update(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("修改SysDeptDTO{}", JSONUtil.toJsonStr(paramMap));

        SysDeptDTO dto=JSON.parseObject(JSON.toJSONString(paramMap), SysDeptDTO.class);
        log.info("修改SysDeptDTO{}", JSONUtil.toJsonStr(dto));

        try {
            ValidatorUtils.validateEntity(dto, new Class[]{UpdateGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        com.sdhs.system.syncdata.util.Result result= (com.sdhs.system.syncdata.util.Result) this.sysDeptService.update(dto);
        log.info("修改机构返回--------"+result);

        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(result), "123456", "AES");
    }
    @PostMapping("/OrgDeleteService")
    public Object OrgDeleteService(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("删除SysDeptDTO{}", JSONUtil.toJsonStr(paramMap));
        SysDeptDTO dto=JSON.parseObject(JSON.toJSONString(paramMap), SysDeptDTO.class);
        log.info("删除SysDeptDTO{}", JSONUtil.toJsonStr(dto));
        try {
            ValidatorUtils.validateEntity(dto, new Class[]{UpdateGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        com.sdhs.system.syncdata.util.Result result=new com.sdhs.system.syncdata.util.Result();

        if(StringUtils.isNotBlank(dto.getBimOrgId())){
            result= (com.sdhs.system.syncdata.util.Result) this.sysDeptService.delete(dto.getBimOrgId());
        }else{
            result.error("请填写要删除的id");
        }
        result.setBimRequestId(dto.getBimRequestId());
        log.info("删除机构返回--------"+result);
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(result), "123456", "AES");
    }


    @PostMapping("/QueryAllOrgIdsService")
    public Object queryAllOrgIdsService(HttpServletRequest request ){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("获取所有机构请求参数{}", JSONUtil.toJsonStr(paramMap));

        QueryParam queryParam=JSON.parseObject(JSON.toJSONString(paramMap), QueryParam.class);
        log.info("获取所有机构请求参数:{}", JSONUtil.toJsonStr(queryParam));

        ResultUser result=new ResultUser();
        result.setBimRequestId(queryParam.getBimRequestId());
        Object allDept = this.sysDeptService.getAllDept(queryParam.getBimRequestId());
        log.info("获取所有机构返回--------"+allDept);
        return allDept;

    }
    @PostMapping("/QueryOrgByIdService")
    public Object queryOrgByIdService(HttpServletRequest request){
        Map<String, Object> paramMap = BambooCloudUtils.getRequestForMap(request);
        log.info("机构详情请求参数{}", JSONUtil.toJsonStr(paramMap));

        QueryParam queryParam=JSON.parseObject(JSON.toJSONString(paramMap), QueryParam.class);
        log.info("机构详情请求参数:{}",JSONUtil.toJsonStr(queryParam));

        Object jsonObject;
        jsonObject= this.sysDeptService.getDeptById(queryParam.getBimRequestId(),queryParam.getBimOrgId());

        log.info("机构详情返回--------"+jsonObject);
        return jsonObject;
    }


    /**
     * 角色暂不同步
     * @param dto
     * @return
     */
    @PostMapping("/RoleCreateService")
    public Object addRole(@RequestBody SysRoleDTO dto){
        log.info("添加SysRoleDTO{}", JSONUtil.toJsonStr(dto));
        try {
            ValidatorUtils.validateEntity(dto, new Class[]{AddGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Object result=  this.sysRoleService.save(dto);

        log.info("新增角色返回--------"+result);
        return result;
    }
    @PostMapping("/RoleUpdateService")
    public Object UpdateRole(@RequestBody SysRoleDTO dto){
        log.info("修改SysRoleDTO{}", JSONUtil.toJsonStr(dto));
        try {
            ValidatorUtils.validateEntity(dto, new Class[]{UpdateGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        com.sdhs.system.syncdata.util.Result result= (com.sdhs.system.syncdata.util.Result) this.sysRoleService.update(dto);
        log.info("修改角色返回--------"+result);
        return result;
    }
    @PostMapping("/RoleDeleteService")
    public Object delete(@RequestBody SysRoleDTO dto){
        log.info("删除SysDeptDTO{}", JSONUtil.toJsonStr(dto));
        try {
            ValidatorUtils.validateEntity(dto, new Class[]{UpdateGroup.class, DefaultGroup.class});
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        com.sdhs.system.syncdata.util.Result result=new com.sdhs.system.syncdata.util.Result();

        if(StringUtils.isNotBlank(dto.getBimRid())){
            result= (com.sdhs.system.syncdata.util.Result) this.sysRoleService.delete(dto.getBimRid());
        }else{
            result.error("请填写要删除的id");
        }
        result.setBimRequestId(dto.getBimRequestId());
        log.info("删除机构返回--------"+result);
        return result;

    }
    @PostMapping("/QueryAllRoleIdsService")
    public Object queryAllRoleIdsService(@RequestBody QueryParam queryParam){
        log.info("获取所有角色请求参数:{}", JSONUtil.toJsonStr(queryParam));

        ResultRole result=new ResultRole();
        result.setBimRequestId(queryParam.getBimRequestId());
        Object allUser = this.sysRoleService.getAllRoleId(queryParam.getBimRequestId());
        log.info("获取所有用户----"+allUser);

        return allUser;
    }

    @PostMapping("/QueryRoleByIdService")
    public Object queryRoleById(@RequestBody QueryParam queryParam){
        log.info("根据ID查询角色数:{}", JSONUtil.toJsonStr(queryParam));
        Object sysRole = this.sysRoleService.getRoleById(queryParam.getBimRequestId(),queryParam.getBimRid());
        log.info("根据ID查询角色----"+sysRole);

        return sysRole;
    }



    @PostMapping("/updateDeptByUser")
    public Object updateDeptByUser(@RequestBody SyncSysUser dto){
        log.info("修改用户机构", JSONUtil.toJsonStr(dto));

        String createor = dto.getBimRemoteUser();
        String deptId =  dto.getDeptId();
        List<String> list=new ArrayList<>();
        list.add(deptId.toString());
        Object sysUserDept = this.sysUserDeptService.updateDeptByUser(dto.getUserName(),list,createor);
        log.info("修改用户机构----"+sysUserDept);
        return sysUserDept;
    }

    Map<String, Object> getParamMap(JSONObject json){
        Map<String, Object> params = new HashMap<>();
        Iterator it =json.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            params.put(entry.getKey(), entry.getValue());
        }
        return params;
    }


    //修改dept表字段
    @PostMapping("updateDeptFileld")
    public R updateDeptFileld(){
        String s = sysDeptService.updateDeptFileld();
        return R.ok(s);
    }
}
